package edu.ntu.im.p2ptrade.msg;

import java.security.PrivateKey;
import java.security.Signature;

import net.jxta.endpoint.Message;
import net.jxta.endpoint.StringMessageElement;
import edu.ntu.im.p2ptrade.P2PTrade;
import edu.ntu.im.p2ptrade.security.KeyManager;

public class AuthenticatedMessageWrapper implements PMessage {
	private PMessage message;

	public static final String DIGITAL_SIGNATURE = "DS";

	public static final String LOGMSG = "logMsg";

	public AuthenticatedMessageWrapper(PMessage pm) {
		this.message = pm;
	}

	public Message getMessageToTransfer() throws Exception {
		Message msg = this.message.getMessageToTransfer();
		addDigitalSignature(msg);
		return msg;
	}

	private void addDigitalSignature(Message msg) {
		try {
			PrivateKey pk = KeyManager.getInstance().getPrivateKey(
					KeyManager.PASSWORD);
			Signature dsa = Signature.getInstance("SHA1withRSA");
			dsa.initSign(pk);
			byte[] content = msg.toString().getBytes();
			dsa.update(content);
			byte[] sig = dsa.sign();

			UserInfo.addByteArrayToMessage(msg, P2PTrade.getInstance()
					.getAppName(), DIGITAL_SIGNATURE, sig, false);
			String logMsg = this.toLogMessage();
			if (logMsg != null) {
				msg.addMessageElement(P2PTrade.getInstance().getAppName(),
						new StringMessageElement(LOGMSG, logMsg,
								null));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String toLogMessage() {
		return this.message.toLogMessage();
	}

}
